GEOG 5201 – Spring 2022
Leaflet is an open-source JavaScript library for interactive web maps. The goal of this lecture is to understand the basics of Leaflet and to create a simple web map using Leaflet. You can find the source code of the web map by right-clicking the web page and clicking View page source (in Chrome).
Before writing any code for the map, we need to do the following preparation steps on our page.
<html>
, <head>
, and <body>
elements.
<html>
<head>
</head>
<body>
</body>
</html>
<head>
element, include Leaflet CSS file (recall how we embed external CSS in HTML):
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
<head>
element, include Leaflet JavaScript file after Leaflet’s CSS (recall how we embed external JavaScript code in HTML):
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<body>
element, put a div
element with a certain id where we want our map to be. Set inline CSS to make sure the map container has a defined height:
<div id="map", style="width: 600px; height: 400px;"></div>
Now we are ready to initialize the map and do some stuff with it.Let’s create a map of the center of London with pretty Mapbox Streets tiles. From here on, we will be working in JavaScript.
<script></script>
tages fter the <div>
element (recall how we embed internal JavaScript code in HTML)Maps in Leaflet are defined by L.map
objects. In the <script>
element, initialize the map by setting it as a new variable (with keyword var
). Set the map view to our chosen geographical coordinates and a zoom level using the setView()
method for object L.map
:
var map = L.map('map').setView([51.505, -0.09], 13);
By default (as we didn’t pass any options when creating the map instance), all mouse and touch interactions on the map are enabled, and it has zoom and attribution controls.
Next, we will add a base map to our map, in this case it is a Mapbox Streets tile layer. Tile layers in Leaflet are defined by L.tileLayer
objects. Creating a tile layer usually involves setting the URL template for the tile images, the attribution text, and the maximum zoom level of the layer. In this example, we will use the mapbox/streets-v11
tiles from Mapbox’s Static Tiles API. We use the addTo()
method for object L.tileLayer
to add the tile layer:
var tiles = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1
}).addTo(map);
Make sure all the code is called after the div and leaflet.js inclusion. That’s it! You have a working Leaflet map now.
Besides tile layers, you can easily add other things to your map, including markers, circles, polygons, polylines, and popups.
L.marker
objects. We can specify the geographic coordinates of the marker and add it to the map using the addTo()
method:
var marker = L.marker([51.5, -0.09]).addTo(map);
L.circle
objects. Adding a circle is the same (except for specifying the radius in meters as a second argument), but lets you control how it looks (e.g., fill color) when creating the object:
var circle = L.circle([51.508, -0.11], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 500
}).addTo(map);
L.polygon
objects. Adding a polygon is as easy:
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(map);
Popups are usually used when you want to attach some information to a particular object on a map.
Leaflet has a very handy shortcut for popups attached to the symbols created previously, which is achieved using the bindPopup()
and openPopup()
methods. The bindPopup()
method attaches a popup with the specified HTML content to your marker so that it appears when you click on the object, and the openPopup()
method (for markers only) immediately opens the attached popup
marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
circle.bindPopup("I am a circle.");
polygon.bindPopup("I am a polygon.");
We can also use popups as layers (when needing something more than attaching a popup to an object) using the objects L.popup
. The openOn()
method adds the popup to the map and closes the previous one.
var popup = L.popup()
.setLatLng([51.513, -0.09])
.setContent("I am a standalone popup.")
.openOn(map);
Each object in Leaflet has its own set of events (see documentation for details). Every time something happens in Leaflet (e.g. the user clicks on a marker or map zoom changes), the corresponding object sends an event which you can subscribe to with a function. For example, we use the on()
method for the map
object and pass the parameters as the event click
and function onMapClick
to handle the event using an alert:
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}
map.on('click', onMapClick);
Let’s improve our example by using a popup instead of an alert:
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
map.on('click', onMapClick);
Now you’ve learned Leaflet basics and can start building map apps straight away! Don’t forget to take a look at the detailed documentation or other examples.